<template>
  <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" :close-on-click-modal="false"
    :before-close="handleClose">
    <div class="form">
      <!-- 表单输入元件 ----------------------------------------------------------------------------------------->
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="rule_form">
        <div class="rule_form_left">
          <el-divider>故障信息</el-divider>
          <el-form-item label="设备所属部门">
            <el-input disabled v-model="ruleForm.equipmentAccountId" />
          </el-form-item>

          <el-form-item label="设备名称">
            <el-input disabled v-model="ruleForm.equipmentAccountId" />
          </el-form-item>

          <el-form-item label="设备编号">
            <el-input disabled v-model="ruleForm.equipmentAccountTitle" />
          </el-form-item>

          <el-form-item label="故障等级">
            <el-input disabled v-model="ruleForm.faultLevel" />
          </el-form-item>

          <el-form-item label="故障类型">
            <el-input disabled v-model="ruleForm.faultType" />
          </el-form-item>

          <el-form-item label="故障描述">
            <el-input disabled type="textarea" :placeholder="isUpdateForm ? '' : '请输入描述'"
              v-model="ruleForm.faultDescribe" maxlength="100" show-word-limit />
          </el-form-item>

          <!-- <el-form-item label="备注">
            <el-input :disabled="isUpdateForm" type="textarea" :placeholder="isUpdateForm?'':'请输入备注'" v-model="ruleForm.remark" maxlength="50" show-word-limit />
          </el-form-item> -->

          <el-form-item label="故障图片">
            <Image-upload :value='ruleForm.repairImagesDetail' :limit="ruleForm.repairImagesDetail.length || 1"
              :isDisabled="['update', 'delete']" />
          </el-form-item>

          <el-form-item label="故障视频">
            <video v-if="ruleForm.faultVideo" ref="videoPlay" :src="ruleForm.faultVideo" width="290" height="203"
              style="background-color: black" controls="controls">
              您的浏览器不支持视频播放
            </video>
            <div v-else>
              -
            </div>
          </el-form-item>
        </div>

        <div class="rule_form_right">
          <el-divider>审核信息</el-divider>
          <el-form-item label="委外服务商" prop="supplierId">
            <el-select v-model="ruleForm.supplierId" placeholder="请选择处理结果" @change="handleSelect">
              <el-option v-for="item in supplierList" :key="item.supplierId" :label="item.supplierName"
                :value="item.supplierId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="联系人">
            <el-input disabled v-model="ruleForm.supplierTitle" />
          </el-form-item>
          <el-form-item label="审核人" prop="auditVosUser">
            <el-select v-model="ruleForm.auditVosUser" collapse-tags multiple placeholder="请选择审核人" style="width:100%">
              <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="" prop="">
            <span v-for="(tag, index) in tagUserList" :key="index">
              <el-tag closable disable-transitions @close="tagChange(tag, index)">
                <span>{{ tag.name }}</span>
              </el-tag>
              <span style="font-size:28px;position: relative;top: 5px;">
                <template v-if="index !== tagUserList.length - 1">
                  <i class="el-icon-caret-right"></i>
                </template>
              </span>
            </span>

          </el-form-item>
          <el-form-item label="抄送人">
            <el-select v-model="ruleForm.auditVosType" multiple placeholder="请选择抄送人" style="width:100%">
              <el-option v-for="dict in allUserData" :key="dict.index" :label="dict.userName" :value="dict.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>

      </el-form>
      <!-- ----------------------------------------------------------------------------------------------------->
    </div>
    <div align="center" class="dialog-footer">
      <el-button type="primary" @click="handleConfirm">提交</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
/** 远程添加，修改，获取单个详性接口，获取selector下拉列表的接口，以及时间转换工具函数等 ------------------------------------------------- */
import { listDetail, updateOutsourceRight, getuserlist, supplierlist } from '@/api/maintenance/management/guySingle.js'
import UploadImage from '@/components/upload/index.vue'
/** ------------------------------------------------------------------------------------------------------------------------------- */

/** 表单参数 ------------------------------------------------------------------------------------------------------------------------ */
const ruleForm = {
  // -------------------------------------展示数据---------------------------------------------------------------
  deptName: '',//设备所属部门
  equipmentAccountId: '', //设备名称
  equipmentAccountTitle: '',//设备编号
  faultLevel: '',//故障等级
  faultType: '', //故障类型
  faultDescribe: "", //故障描述
  repairImagesDetail: [],
  faultVideo: '',
  //-------------------------------------需提交的表单数据-------------------------------------------------------------
  supplierTitle: '',//联系人名称，用于展示
  supplierId: '',//委外服务商id
  auditVosUser: [],//审核人集合
  auditVosType: [],//抄送人 
}
/** ---------------------------------------------------------------------------------------------------------------------------------- */
// 提交处理完毕处理函数-----------------------------
function processRuleForm (ruleForm) {
  const data = Object.assign({}, ruleForm)
  delete data.deptName
  delete data.equipmentAccountId
  delete data.equipmentAccountTitle
  delete data.faultLevel
  delete data.faultType
  delete data.faultDescribe
  delete data.repairImagesDetail
  delete data.faultVideo
  delete data.supplierTitle
  delete data.auditVosType
  delete data.auditVosUser
  const rule1 = ruleForm.auditVosUser.map(item => {
    return {
      userId: item,
      userType: '0'
    }
  })
  const rule2 = ruleForm.auditVosType.map(item => {
    return {
      userId: item,
      userType: '1'
    }
  })
  data.auditVos = [...rule1, ...rule2]
  console.log(data);
  return data
}

export default {
  name: 'Form',
  components: {
    UploadImage
  },
  data () {
    return {
      dialogVisible: false,
      ruleForm: Object.assign({}, ruleForm),
      isUpdateForm: false,
      dialogTitle: '',
      supplierList: [],//委外服务商数组
      allUserData: [],//审核人 和 抄送人 数组
      /** 表单规则 --------------------------------------------------------------------------------------------------------------------- */
      rules: {
        supplierId: [
          { required: true, message: '请选择委外服务商', trigger: 'change' }
        ],
        auditVosUser: [
          { required: true, message: '请选择审核人', trigger: 'change' }
        ],
        auditVosType: [
          { required: true, message: '请选择抄送人', trigger: 'change' }
        ],
      }
      /** ----------------------------------------------------------------------------------------------------------------------------- */
    }
  },
  computed: {
    // 审核人数据转换--------------------------
    tagUserList () {
      let Arr = []
      this.ruleForm.auditVosUser.map(item => {
        this.allUserData.map(value => {
          if (item === value.userId) {
            Arr.push({
              userId: value.userId,
              name: value.userName
            })
          }
        })
      })
      return Arr
    },
  },
  methods: {
    // 处理结果操作函数------------------
    handleSelect (id) {
      const rule = this.supplierList.filter(item => item.supplierId == id).map(item => item.liaison + '（' + item.phone + '）').join()
      this.ruleForm.supplierTitle = rule
    },
    async getlist () {
      // 用户列表和委外服务商接口-------------------------
      const userdata = await getuserlist();
      const superdata = await supplierlist()
      this.allUserData = userdata.data
      this.supplierList = superdata.data
    },

    // 审核人删除事件
    tagChange (val, index) {
      this.ruleForm.auditVosUser.splice(index, 1)
    },
    // 打开表单对话框
    openDialog (id = null) {
      if (id) {
        listDetail(id).then(res => {
          this.getlist()
          this.isUpdateForm = true
          this.dialogTitle = '转委外单'
          this.$set(this.ruleForm, 'repairId', id)
          this.ruleForm.deptName = res.data.repairEquipmentAccountVo.eaPartInfoVo.deptName
          this.ruleForm.equipmentAccountId = res.data.repairEquipmentAccountVo.eaPartInfoVo.equipmentName
          this.ruleForm.equipmentAccountTitle = res.data.repairEquipmentAccountVo.eaPartInfoVo.equipmentNum
          this.ruleForm.faultLevel = ['紧急', '严重', '一般'][res.data.faultLevel]
          this.ruleForm.faultType = res.data.faultTypeName
          this.ruleForm.faultDescribe = res.data.faultDescribe
          this.ruleForm.repairImagesDetail = res.data.repairImages.filter(item => item.type == 0).map(item => item.image)
          this.ruleForm.faultVideo = res.data.faultVideo
          // this.ruleForm.remark = res.data.remark
          this.dialogVisible = true
        })
      }
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = processRuleForm(this.ruleForm)
          updateOutsourceRight(data).then((res) => {
            this.$message({
              message: '转委外单成功！',
              type: 'success'
            })
            this.resetForm('ruleForm')
            this.dialogVisible = false
            this.$emit('submit_success')
          })
        } else {
          this.$message({
            message: '数据验证不通过，检查输入表单',
            type: 'error'
          })
          return false
        }
      })
    },
    /** ---------------------------------------------------------------------------------------------------------------------------------------- */
    // 关闭窗口，重置表单
    handleClose () {
      this.ruleForm = Object.assign({}, ruleForm)
      this.$nextTick(function () {
        this.$refs['ruleForm'].clearValidate()
      });
      this.dialogVisible = false
    },
    handleConfirm () {
      this.submitForm('ruleForm')
    },
    resetForm () {
      this.handleClose()
    }
  }
}
</script>
<style lang="scss" scoped>
.form {
  .inventory {
    display: flex;
  }
}

::v-deep .el-input-number__decrease {
  display: none;
}

::v-deep .el-input-number__increase {
  display: none;
}

::v-deep .el-select {
  width: 100%;
}

::v-deep .el-input-number {
  width: 100%;
}

.rule_form {
  display: flex;

  &_left {
    flex: 1;
    margin-right: 20px;
  }

  &_right {
    flex: 1
  }
}
</style>
